﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using IchiaTester.Utils;

namespace IchiaTester
{
    public partial class SystemConfigForm : Form
    {
        private MainForm mainForm;
        private DataManager dataManager;


        public SystemConfigForm(MainForm form, DataManager dataManager)
        {
            mainForm = form;
            this.dataManager = dataManager;
            InitializeComponent();
        }

        private void SystemConfigForm_Load(object sender, EventArgs e)
        {
            try
            {
                MainForm.InfoLogAppend($"Try to setup system config form...", MainForm.SystemState.GetValue);
                tbWorkerID.Text = SystemSetting.workId;                        //工號
                tbWorkshift.Text = SystemSetting.workShift;                    //班別
                tbProductId.Text = SystemSetting.productId;                    //產品編號
                tbWorkOrder.Text = SystemSetting.workOrder;                    //工單號
                tbProcessOrder.Text = SystemSetting.processOrder;              //製程編號
                tbBoardNum.Text = SystemSetting.boardNum;                      //多版數
                tbProductKey.Text = SystemSetting.productkey;                  //產品key
                tbJigId.Text = SystemSetting.jigId;                            //治具編號
                tbMachineId.Text = SystemSetting.machineId;                    //機器編號
                tbAppName.Text = SystemSetting.appName;                        //程式名稱
                tbAppVersion.Text = SystemSetting.appVersion;                  //版本
                tbTimeout.Text = string.Empty;                        //Timeout
                numDelayToStart.Value = string.IsNullOrEmpty(SystemSetting.delayToStartTest) ? 0 : decimal.Parse(SystemSetting.delayToStartTest);
                numDelayToWait.Value = string.IsNullOrEmpty(SystemSetting.delayToWait) ? 0 : decimal.Parse(SystemSetting.delayToWait);

                CkbStartButton.Checked = false;
                CkbBarcodeDetect.Checked = false;
                CkbDeviceCMD.Checked = false;
                CkbAskDevice.Checked = false;
                bool.TryParse(SystemSetting.keepTestCheck, out bool ktc);
                bool.TryParse(SystemSetting.startButtonCheck, out bool sbc);
                bool.TryParse(SystemSetting.barcodeDetectCheck, out bool bdc);
                bool.TryParse(SystemSetting.deviceCMDCheck, out bool dcc);
                bool.TryParse(SystemSetting.askDeviceCheck, out bool adc);
                CkbKeepTest.Checked = ktc;
                CkbStartButton.Checked = sbc;
                CkbBarcodeDetect.Checked = bdc;
                CkbDeviceCMD.Checked =  dcc;
                CkbAskDevice.Checked = adc;
                gbDeviceCMD.Enabled = CkbDeviceCMD.Checked;
                panelAskDevice.Enabled = CkbAskDevice.Checked;
                tbBarcodeLength.Enabled = CkbBarcodeDetect.Checked;
                tbBarcodeLength.Text = SystemSetting.barcodeLength;            //Barcode length 
                tbAskDeviceCMD.Text = SystemSetting.askDeviceCMD;              //ask device cmd
                numAskDeviceFreq.Value = string.IsNullOrEmpty(SystemSetting.askDeviceFreq) ? 0 : decimal.Parse(SystemSetting.askDeviceFreq); //ask device freq
                tbStartTestCMD.Text = SystemSetting.askDeviceReturnCMD;        //ask device return cmd
                cbAskDeviceCOM.Items.Clear();
                cbAskDeviceReturnCOM.Items.Clear();
                List<string> comPorts = SerialPortHandler.GetAvailableComPorts();
                for (int i = 0; i < comPorts.Count; i++)
                {
                    cbAskDeviceCOM.Items.Add(comPorts[i]);
                    cbAskDeviceReturnCOM.Items.Add(comPorts[i]);
                }
                //Check if the port is available
                if (comPorts.Contains(SystemSetting.askDevicePort))
                {
                    cbAskDeviceCOM.SelectedIndex = cbAskDeviceCOM.Items.IndexOf(SystemSetting.askDevicePort);
                }
                else 
                {
                    cbAskDeviceCOM.SelectedIndex = -1;
                }
                if (comPorts.Contains(SystemSetting.askDeviceReturnPort))
                {
                    cbAskDeviceReturnCOM.SelectedIndex = cbAskDeviceReturnCOM.Items.IndexOf(SystemSetting.askDeviceReturnPort);
                }
                else
                {
                    cbAskDeviceReturnCOM.SelectedIndex = -1;
                }



                if (string.IsNullOrEmpty(SystemSetting.clearAfterTest))
                { ckBClearAfterTest.Checked = false; }
                else
                { ckBClearAfterTest.Checked = SystemSetting.clearAfterTest == "1" ? true : false; }

                tbFactoryLogFolder.Text = SystemSetting.factoryLogPath;
                tbAppLogFolder.Text = SystemSetting.appLogPath;
                MainForm.InfoLogAppend($"System config form setup successfully.", MainForm.SystemState.GetValueSuccess);
            }
            catch (Exception ex)
            {
                MainForm.ErrorLogAppend("Fail to setup system config form!", ex.Message + ex.StackTrace, MainForm.SystemState.ErrorHandling);
                MessageBox.Show("Fail to setup system config form! Please check the log file for more information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void SystemConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            string oldPath = Path.Combine(SystemSetting.appLogPath, SystemSetting.appLogFilename);

            SystemSetting.workId = tbWorkerID.Text;                        //工號
            SystemSetting.workShift = tbWorkshift.Text;                    //班別
            SystemSetting.productId = tbProductId.Text;                    //產品編號
            SystemSetting.workOrder = tbWorkOrder.Text;                    //工單號
            SystemSetting.processOrder = tbProcessOrder.Text;              //製程編號
            SystemSetting.boardNum = tbBoardNum.Text;                      //多版數
            SystemSetting.productkey = tbProductKey.Text;                  //產品key 
            SystemSetting.jigId = tbJigId.Text;                            //治具編號
            SystemSetting.machineId = tbMachineId.Text;                    //機器編號
            SystemSetting.appName = tbAppName.Text;                        //程式名稱
            SystemSetting.appVersion = tbAppVersion.Text;                  //版本
            SystemSetting.delayToStartTest = numDelayToStart.Value.ToString();
            SystemSetting.delayToWait = numDelayToWait.Value.ToString();
            SystemSetting.clearAfterTest = ckBClearAfterTest.Checked ? "1" : "0";
            SystemSetting.factoryLogPath = tbFactoryLogFolder.Text;
            SystemSetting.appLogPath = tbAppLogFolder.Text;

            SystemSetting.barcodeLength = tbBarcodeLength.Text;            //barcode length 
            SystemSetting.askDeviceCMD = tbAskDeviceCMD.Text;              //ask device cmd
            SystemSetting.askDeviceFreq = numAskDeviceFreq.Value.ToString(); //ask device freq
            SystemSetting.askDeviceReturnCMD = tbStartTestCMD.Text;        //ask device return cmd

            //更改App log路徑
            dataManager.RelocateAppLog(oldPath);

            //save setting
            dataManager.SaveSettingsToIniFile();

            //Update info
            mainForm.DisplayWorkerInfo();
            this.DialogResult = DialogResult.OK;
        }

        private void btnLogFolder_Click(object sender, EventArgs e)
        {
            // 創建 FolderBrowserDialog
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 打開對話方塊，並檢查使用者是否選擇
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                tbFactoryLogFolder.Text = folderBrowserDialog.SelectedPath;
            }
        }
        private void btnAppLogFolder_Click(object sender, EventArgs e)
        {

            // 創建 FolderBrowserDialog
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 打開對話方塊，並檢查使用者是否選擇
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                tbAppLogFolder.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnDefaultApp_Click(object sender, EventArgs e)
        {
            SystemSetting.appLogPath = Application.StartupPath + "\\" + "App log";
            if (FileHandler.CheckDirectory(SystemSetting.appLogPath))
            {
                tbAppLogFolder.Text = SystemSetting.appLogPath;
            }
            else
            {
                //Create folder
                Directory.CreateDirectory(SystemSetting.appLogPath);
                tbAppLogFolder.Text = SystemSetting.appLogPath;
            }
            
        }

        private void btnDefaultFactory_Click(object sender, EventArgs e)
        {
            SystemSetting.factoryLogPath = Application.StartupPath + "\\" + "Factory log";
            if (FileHandler.CheckDirectory(SystemSetting.factoryLogPath))
            {
                tbFactoryLogFolder.Text = SystemSetting.factoryLogPath;
            }
            else
            {
                //Create folder
                Directory.CreateDirectory(SystemSetting.factoryLogPath);
                tbFactoryLogFolder.Text = SystemSetting.factoryLogPath;
            }
        }

        private void CkbStartButton_CheckedChanged(object sender, EventArgs e)
        {
            if (CkbStartButton.Checked)
            {
               SystemSetting.startButtonCheck = CkbStartButton.Checked.ToString();
            }
            else
            {
                SystemSetting.startButtonCheck = CkbStartButton.Checked.ToString();

            }
        }

        private void CkbBarcodeDetect_CheckedChanged(object sender, EventArgs e)
        {
            if(CkbBarcodeDetect.Checked)
            {
                tbBarcodeLength.Enabled = CkbBarcodeDetect.Checked;
            }
            else
            {
                tbBarcodeLength.Enabled = CkbBarcodeDetect.Checked;
                tbBarcodeLength.Text = "";
            }
            SystemSetting.barcodeDetectCheck = CkbBarcodeDetect.Checked.ToString();
        }

        private void CkbDeviceCMD_CheckedChanged(object sender, EventArgs e)
        {
            if (CkbDeviceCMD.Checked)
            {
                List<string> comPorts = SerialPortHandler.GetAvailableComPorts();
                cbAskDeviceCOM.Items.Clear();
                cbAskDeviceReturnCOM.Items.Clear();
                for (int i = 0; i < comPorts.Count; i++)
                {
                    cbAskDeviceCOM.Items.Add(comPorts[i]);
                    cbAskDeviceReturnCOM.Items.Add(comPorts[i]);
                }
                gbDeviceCMD.Enabled = CkbDeviceCMD.Checked;
                
            }
            else
            {
                gbDeviceCMD.Enabled = CkbDeviceCMD.Checked;
                CkbAskDevice.Checked = false;
                cbAskDeviceReturnCOM.SelectedIndex = -1;
                tbStartTestCMD.Text = "";
            }
            SystemSetting.deviceCMDCheck = CkbDeviceCMD.Checked.ToString();
        }

        private void CkbAskDevice_CheckedChanged(object sender, EventArgs e)
        {
            if (CkbAskDevice.Checked)
            {
                panelAskDevice.Enabled = CkbAskDevice.Checked;
            }
            else
            {
                panelAskDevice.Enabled = CkbAskDevice.Checked;
                numAskDeviceFreq.Value = 0;
                cbAskDeviceCOM.SelectedIndex = -1;
                tbAskDeviceCMD.Text = "";
            }
            SystemSetting.askDeviceCheck = CkbAskDevice.Checked.ToString();
        }

        private void cbAskDeviceCOM_SelectedIndexChanged(object sender, EventArgs e)
        {
            SystemSetting.askDevicePort = cbAskDeviceCOM.Text;
        }

        private void cbAskDeviceReturnCOM_SelectedIndexChanged(object sender, EventArgs e)
        {
            SystemSetting.askDeviceReturnPort = cbAskDeviceReturnCOM.Text;
        }

        private void CkbKeepTest_CheckedChanged(object sender, EventArgs e)
        {
            SystemSetting.keepTestCheck = CkbKeepTest.Checked.ToString();
        }
    }
}
